package com.etoak.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etoak.common.core.enums.OrderStateEnum;
import com.etoak.entity.Order;
import com.etoak.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CancelService {

    @Autowired
    OrderMapper orderMapper;

    @RabbitListener(queues = "order")
    public void cancel(String orderNo) {
        log.info("orderNo is {}", orderNo);
        Order order = getOrder(orderNo);
        if (ObjectUtils.isNotEmpty(order) &&
                order.getOrderState().equals(OrderStateEnum.CREATE.getState())) {
            // 设置状态为取消
            order.setOrderState(OrderStateEnum.CANCEL.getState());
            order.setCancelTime(DateUtil.now());
            order.setCancelReason("自动取消!");

            orderMapper.updateById(order);
        }
    }

    private Order getOrder(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        return orderMapper.selectOne(queryWrapper);
    }
}
